
package com.fhc.todoapp.start2

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.animateIntAsState
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.MaterialTheme
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberTopAppBarState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.fhc.todoapp.R
import com.fhc.todoapp.TodoApplication.AppViewModel
import com.fhc.todoapp.data.Task
import com.fhc.todoapp.ui.SunflowerTheme
import com.fhc.todoapp.util.EventDataTest
import com.fhc.todoapp.util.EventDataTest2
import com.fhc.todoapp.util.FlowEventBusData
import com.fhc.todoapp.util.LoadingContent
import com.fhc.todoapp.util.TestFlowEventBus
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import no.nordicsemi.android.common.permissions.ble.RequireBluetooth
import no.nordicsemi.android.common.permissions.ble.RequireLocation
import timber.log.Timber
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import com.fhc.todoapp.util.NoBluetoothView
import com.fhc.todoapp.util.SvgIcon
import com.fhc.todoapp.util.ToastyShow
import kotlinx.coroutines.delay


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CenterAlignedTopAppBarExample(viewModel: StartViewModel?) {
    val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior(rememberTopAppBarState())
//
//    Scaffold(
//        modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
//
//        topBar = {
//
//        },
//    ) { innerPadding ->
//        ScrollContent(innerPadding)
//    }
    CenterAlignedTopAppBar(
        colors = TopAppBarDefaults.centerAlignedTopAppBarColors(
            containerColor = MaterialTheme.colorScheme.primaryContainer,
            titleContentColor = MaterialTheme.colorScheme.primary,
        ),
        title = {
            Text(
                stringResource(id = R.string.task_details),
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        },
        navigationIcon = {
            IconButton(onClick = { /* do something */ }) {
                Icon(
                    imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                    contentDescription = "Localized description"
                )
            }
        },
        actions = {
            IconButton(onClick = {
//                viewModel?.deleteTask()
                viewModel?.loadDialog()
            }) {
                Icon(Icons.Filled.Delete, null)
            }
            if(viewModel != null){
//                val uiState by viewModel.uiState.collectAsStateWithLifecycle()
//                if (uiState.isTaskDeleted) {
//                    IconButton(onClick = viewModel::deleteTask) {
//                        Icon(Icons.Filled.AccountBox, null)
//                    }
//                }
            }
        },
        modifier = Modifier.fillMaxWidth(),
        scrollBehavior = scrollBehavior,
    )
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun StartTopAppBar(viewModel: StartViewModel?) {
    //CenterAlignedTopAppBar
    TopAppBar(
        title = {
            Text(text = stringResource(id = R.string.task_details))
        },
        actions = {
            IconButton(onClick = {
//                viewModel?.deleteTask()
                viewModel?.loadDialog()
            }) {
                Icon(Icons.Filled.Delete, null)
            }

            IconButton(onClick = {
                viewModel?.addPage()
            }) {
                Icon(Icons.Filled.Add, null)
            }

            if(viewModel != null){
//                val uiState by viewModel.uiState.collectAsStateWithLifecycle()
//                if (uiState.isTaskDeleted) {
//                    IconButton(onClick = {
////                        viewModel::deleteTask
//
//                    }) {
//                        Icon(Icons.Filled.AccountBox, null)
//                    }
//                }
            }
        },
        modifier = Modifier.fillMaxWidth(),
//        backgroundColor = colorScheme.primary

        colors = TopAppBarDefaults.centerAlignedTopAppBarColors(
            containerColor = colorScheme.primary,
            titleContentColor = Color.White,
        ),
    )
}

@Composable
private fun TextInput(viewModel: StartViewModel){
    val alertState by viewModel.alertState.collectAsStateWithLifecycle()
    TextField(
        value = alertState.title,
        onValueChange = {
            viewModel.alertTitle(it)
        },
        textStyle = TextStyle(
            fontSize = 16.sp, color = Color.Blue
        ),
    )
}

@Composable
private fun StartContent(
    viewModel: StartViewModel?,
    scaffoldState: SnackbarHostState?,
    loading: Boolean,
    empty: Boolean,
    task: Task?,
//    onTaskCheck: (Boolean) -> Unit,
//    onRefresh: () -> Unit,
    modifier: Modifier = Modifier
) {
    RequireBluetooth(
        onChanged = { it->{
            Timber.tag("StartContent").e("RequireBluetooth   onChanged   >>>>>>$it")
        } },
        contentWithoutBluetooth = {it->
            Timber.tag("StartContent").e("contentWithoutBluetooth      11111111111>>>>>>$it")
            NoBluetoothView(it)
        }
    ) {
        Timber.tag("StartContent").e("contentWithoutBluetooth      22222222222>>>>>>")
        RequireLocation(
            onChanged = { it->{
                Timber.tag("StartContent").e("RequireLocation   onChanged   >>>>>>$it")
            } },
            contentWithoutLocation = {
            }
        ) { isLocationRequiredAndDisabled ->
            Timber.tag("StartContent").e("isLocationRequiredAndDisabled   >>>>>>$isLocationRequiredAndDisabled")
            val snackbarCoroutineScope = rememberCoroutineScope()
//    var inputPhone by remember { mutableStateOf("Hello\nWorld\nInvisible") }
            val screenPadding = Modifier.padding(
                horizontal = dimensionResource(id = R.dimen.horizontal_margin),
                vertical = dimensionResource(id = R.dimen.vertical_margin),
            )

            val commonModifier = modifier
                .fillMaxWidth()
                .then(screenPadding)

            LoadingContent(
                loading = loading,
                empty = empty,
                emptyContent = {
                    Text(
                        text = stringResource(id = R.string.no_data),
                        modifier = commonModifier
                    )
                },
                onRefresh = {}
            ) {
                Column(commonModifier.verticalScroll(rememberScrollState())) {
                    Row(Modifier
                        .fillMaxWidth()
                        .then(screenPadding)) {
                        if (task != null) {
//                            Checkbox(task.isCompleted, onTaskCheck)
                            Column {
                                Text(text = task.title, style = MaterialTheme.typography.bodyLarge)
                                Text(text = task.description, style = MaterialTheme.typography.bodySmall)
                            }
                        }
                    }
                    if(viewModel != null) {



                        PaginationExample(
                            onItemClick = {item->
                                snackbarCoroutineScope.launch{
                                    scaffoldState?.showSnackbar(item)
                                }
                            }, viewModel, scaffoldState)


                        TextInput(viewModel)
                    }
                }
            }
        }
    }

}

@Composable
fun PaginationExample(
    onItemClick: (String) -> Unit, viewModel: StartViewModel?, scaffoldState: SnackbarHostState?) {
    if(viewModel != null){
        val coroutineScope = rememberCoroutineScope()
        val pageTask by viewModel.pageTask.collectAsStateWithLifecycle()
        val listState = rememberLazyListState()



        LazyColumn(
            state = listState,
            modifier = Modifier.fillMaxWidth().height(200.dp),
            verticalArrangement = Arrangement.spacedBy(10.dp),

        ) {
            if (pageTask.errMessage == null) {
                items(pageTask.data) { item ->
                    Box(modifier = Modifier.fillMaxWidth().clickable {onItemClick(item)}) {
                        // 这里添加你的条目布局代码
                        Text(text = item, modifier = Modifier.padding(10.dp))
                        HorizontalDivider(thickness = 1.dp,color = Color.Black)
                    }
                }

            }
            item {
                if (pageTask.isLoading) {
                    Box(modifier = Modifier
                        .fillMaxWidth()
                        .padding(10.dp), contentAlignment = Alignment.Center) {
                        CircularProgressIndicator(modifier = Modifier.size(50.dp), strokeWidth = 2.dp)
                    }
                }
            }

        }
//        LaunchedEffect(pageTask.data) {
//            Timber.tag("addPage").e(" ----------------------   LaunchedEffect(listState) totalItemsCount ：%s  ：%s", pageTask.data.size, listState.layoutInfo.visibleItemsInfo.size)
//            if( pageTask.data.size > 5) {
//                listState.animateScrollToItem(index = pageTask.data.size - 5)
//            }
//        }
        val visibleItems = 5
        val offsetItemsToAutoLoad = 1

        LaunchedEffect(listState) {
            snapshotFlow { listState.layoutInfo.totalItemsCount }
                .collectLatest { totalItemsCount ->

                    //因为listview 占五行高度item可见
                    Timber.tag(" totalItemsCount").e(" ----------------------    ：%s  ：%s  ：%s", pageTask.data.size, listState.layoutInfo.totalItemsCount, totalItemsCount)
                    if(!pageTask.isLoading && listState.layoutInfo.totalItemsCount > visibleItems) {
                        listState.animateScrollToItem(index = listState.layoutInfo.totalItemsCount - visibleItems- offsetItemsToAutoLoad - 1)
                    }
                }
        }
//        LaunchedEffect(key1 = pageTask.pageIndex) {
//            viewModel.addPage(pageTask.pageIndex)
////            viewModel.addPageAsync()
//        }
        // ！！！ 如果没有load more   animateScrollToItem的index设置为listState.layoutInfo.totalItemsCount
        // Observe scroll state to load more items
        LaunchedEffect(listState) {
            snapshotFlow { listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index }
                .collectLatest { index ->
                    if (!pageTask.isLoading && index != null && index >= pageTask.data.size - offsetItemsToAutoLoad) {
                        viewModel.addPage()
                    }
                }
        }
    }

}



@Composable
fun StartScreen(
    appViewModel: AppViewModel,
    onHistory: (String) -> Unit,
    onScan: () -> Unit,
    modifier: Modifier = Modifier,
    viewModel: StartViewModel = hiltViewModel(),
    scaffoldState: SnackbarHostState = remember { SnackbarHostState() }
) {
//    val lifecycleOwner = LocalLifecycleOwner.current
//    val _appViewModel = ViewModelProvider(lifecycleOwner, TodoApplication.viewModelFactory)[AppViewModel::class.java]
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()
    val alertState by viewModel.alertState.collectAsStateWithLifecycle()

    if(uiState.toastMsgId != null){
        ToastyShow(msgRes = uiState.toastMsgId!!, showAfter = {
            viewModel.snackbarMessageShown()
        })
    }
    Box{
        if (alertState.showDialog) {
            AlertDialog(
                onDismissRequest = { viewModel.showDialog(false) },
                title = { Text(alertState.title) },
                text = { Text("This action cannot be undone") },
                confirmButton = {
                    TextButton(onClick = {viewModel.showDialog(false)}) {
                        Text("Delete it".uppercase())
                    }
                },
                dismissButton = {
                    TextButton(onClick = { viewModel.showDialog(false)}) {
                        Text("Cancel".uppercase())
                    }
                },
            )
        }
//    CircularProgressIndicator()
        Scaffold(
            snackbarHost = { SnackbarHost(scaffoldState) },
            modifier = modifier.fillMaxSize(),
            topBar = {
                StartTopAppBar(viewModel )
            },
            floatingActionButton = {
                FloatingActionButton(onClick = {
                    Timber.tag("LaunchedEffect").e("onScan   >>>>>>FloatingActionButton")
                    onScan()
                }) {
                    Icon(Icons.Filled.Refresh, stringResource(id = R.string.edit_task))
                }
            }
        ) { paddingValues ->

            StartContent(
                viewModel = viewModel,
                scaffoldState = scaffoldState,
                loading = true,
                empty = false,
                task = null,
//                onRefresh = viewModel::refresh,
//                onTaskCheck = viewModel::setCompleted,
                modifier = Modifier.padding(paddingValues)
            )

//            // Check for user messages to display on the screen
//            uiState.errMessage?.let { toastMsg ->
//                val errMessage = stringResource(toastMsg)
//                LaunchedEffect(scaffoldState, viewModel, toastMsg, errMessage) {
//                    scaffoldState.showSnackbar(errMessage)
//                    viewModel.snackbarMessageShown()
//                }
//            }

//            // Check if the task is deleted and call onDeleteTask
//            LaunchedEffect(uiState.isTaskDeleted) {
//                Timber.tag("LaunchedEffect").e(">>>>>>isTaskDeleted:%s", uiState.isTaskDeleted)
////            if (uiState.isTaskDeleted) {
////                onScan()
////            }
//            }


            // 1、获取当前LifecycleOwner（即Activity或Fragment）
            val lifecycleOwner = LocalLifecycleOwner.current
//        val lifecycleState by lifecycleOwner.lifecycle.currentStateFlow.collectAsState()
//        LaunchedEffect(lifecycleState) {
//            // Do something with your state
//            // You may want to use DisposableEffect or other alternatives
//            // instead of LaunchedEffect
//            when (lifecycleState) {
//                Lifecycle.State.DESTROYED -> {
//                    Timber.tag("LocalLifecycleOwner").e("   >>>>>>DESTROYED")
//                }
//                Lifecycle.State.INITIALIZED -> {
//                    Timber.tag("LocalLifecycleOwner").e("   >>>>>>INITIALIZED")}
//                Lifecycle.State.CREATED -> {
//                    Timber.tag("LocalLifecycleOwner").e("   >>>>>>CREATED")}
//                Lifecycle.State.STARTED -> {
//                    Timber.tag("LocalLifecycleOwner").e("   >>>>>>STARTED")}
//                Lifecycle.State.RESUMED -> {
//                    Timber.tag("LocalLifecycleOwner").e("   >>>>>>RESUMED")}
//            }
//        }


            // 2、使用DisposableEffect来处理生命周期事件
            DisposableEffect(lifecycleOwner) {
                // 3.2实现的方法二：
                val observer = LifecycleEventObserver { _, event ->
                    when (event) {
                        Lifecycle.Event.ON_CREATE -> {
                            Timber.tag("LocalLifecycleOwner").e("   >>>>>>ON_CREATE")}
                        Lifecycle.Event.ON_START -> {
                            Timber.tag("LocalLifecycleOwner").e("   >>>>>>ON_START")}
                        Lifecycle.Event.ON_RESUME -> {
                            CoroutineScope(Dispatchers.Default).launch {
                                TestFlowEventBus.subscribe<FlowEventBusData> {event->
                                    if(event.dataObj is EventDataTest){
                                        Timber.tag("FlowEventBus  FlowEventBusData ").e("FlowEventBusData=    ${event.dataObj.firstName}  ${event.dataObj.lastName}")
                                    }else if(event.dataObj is EventDataTest2){
                                        Timber.tag("FlowEventBus  FlowEventBusData ").e("FlowEventBusData=    ${event.dataObj.aaa}   ${event.dataObj.bbb}")
                                    }
                                }
                            }
                            Timber.tag("LocalLifecycleOwner").e("   >>>>>>ON_RESUME")}
                        Lifecycle.Event.ON_PAUSE -> {
                            Timber.tag("LocalLifecycleOwner").e("   >>>>>>ON_PAUSE")}
                        Lifecycle.Event.ON_STOP -> {
                            Timber.tag("LocalLifecycleOwner").e("   >>>>>>ON_STOP")}
                        Lifecycle.Event.ON_DESTROY -> {
                            Timber.tag("LocalLifecycleOwner").e("   >>>>>>ON_DESTROY")}
                        else -> {
                            Timber.tag("LocalLifecycleOwner").e("   >>>>>>elseelseelseelse")}
                    }
                }
                // 3.2实现的方法二：
                lifecycleOwner.lifecycle.addObserver(observer)

                // 4、退离Composition时执行的清理操作
                onDispose {
                    Timber.tag("onDispose").e("   >>>>>>onDispose")
                    lifecycleOwner.lifecycle.removeObserver(observer)
                }
            }
        }
        SplashScreen()
    }


}


@Composable
private fun SplashScreen(){
    val isAnimDone  = remember { mutableStateOf(true) }
    val isSplashMode = remember { mutableStateOf(true) }  //如果不需要后端viewmodel处理，可以用这个控制动画
    if (isAnimDone.value) {
        val isAnimDone  = remember { mutableStateOf(true) }
        val splashTxt  = remember { mutableStateOf("") }
        val str = stringResource(id = R.string.app_name)
        //logo每个文字间隔0.2秒显示
        LaunchedEffect(true){
            for(i in 0..str.length){
                delay(200)
                splashTxt.value = str.substring(0 ,i)
            }
        }
        //1.5秒后开始logo等动画的变化
        LaunchedEffect(true){
            delay(1500)
            isAnimDone .value = !isAnimDone .value
        }
        //3秒后关闭splash动画。splash关闭耗时1秒
        LaunchedEffect(true){
            delay(3000)
            isSplashMode.value = !isSplashMode.value
        }

        val sizeTxt by animateDpAsState(targetValue = if (isAnimDone.value) 40.dp else 0.dp, animationSpec = tween(durationMillis = 500))
        val zoomInImg by animateDpAsState(targetValue = if (isAnimDone.value) 0.dp else 180.dp, animationSpec = tween(durationMillis = 500))
        val zoomOutImg by animateDpAsState(targetValue = if (isAnimDone.value) 180.dp else 0.dp, animationSpec = tween(durationMillis = 500))
        val spTxt by animateIntAsState(targetValue = if (isAnimDone.value) 20 else 0, animationSpec = tween(durationMillis = 500))
        AnimatedVisibility( visible = isSplashMode.value, enter = fadeIn(initialAlpha = 0f), exit = fadeOut(animationSpec = tween(durationMillis = 1000) ,targetAlpha = 0f) ) {
            Column(
                modifier = Modifier.fillMaxSize().background(Color.White),
                verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
                horizontalAlignment = Alignment.CenterHorizontally,

                ) {
                SvgIcon(
                    path = "svg/logo.svg",
                    contentDescription = null,
                    modifier = Modifier.size(zoomInImg),
                )
                Image(
                    painter =  painterResource(id = R.drawable.hero),
                    contentDescription = null,
                    modifier = Modifier.size(zoomOutImg).offset(x = zoomOutImg/6),//图片非主体居中，偏移估测大概量
                )
//                    Image(
//                        painter = rememberVectorPainter(image = Icons.Default.Bluetooth),
//                        contentDescription = null,
//                        modifier = Modifier.size(sizeImg),
//                        colorFilter = ColorFilter.tint(Color.Green.copy(alpha = 1.0f)),
//                    )
                Text( modifier = Modifier.fillMaxWidth().height(sizeTxt),
                    text = splashTxt.value,
                    textAlign = TextAlign.Center,
                    fontSize = spTxt.sp,
                    style = MaterialTheme.typography.titleLarge)
            }
        }
    }

}

@Composable
private fun CircularProgressAnimated(){
    val progressValue = 0.75f
    val infiniteTransition = rememberInfiniteTransition()

    val progressAnimationValue by infiniteTransition.animateFloat(
        initialValue = 0.0f,
        targetValue = progressValue,animationSpec = infiniteRepeatable(animation = tween(900)))

    CircularProgressIndicator(progress = {progressAnimationValue})
}



@Preview
@Composable
private fun StartTopAppBarPreview() {
    SunflowerTheme {
        Surface {
            StartTopAppBar(null)
        }
    }
}


@Preview
@Composable
private fun EditTaskContentPreview() {
    SunflowerTheme {
        Surface {
            StartContent(
                viewModel = null,
                scaffoldState = null,
                loading = false,
                empty = false,
                Task(
                    title = "Title",
                    description = "Description",
                    isCompleted = false,
                    id = "ID"
                ),
//                onTaskCheck = { },
//                onRefresh = { }
            )
        }
    }
}

@Preview
@Composable
private fun EditTaskContentTaskCompletedPreview() {
    SunflowerTheme {
        Surface {
            StartContent(
                viewModel = null,
                scaffoldState = null,
                loading = false,
                empty = false,
                Task(
                    title = "Title",
                    description = "Description",
                    isCompleted = false,
                    id = "ID"
                ),
//                onTaskCheck = { },
//                onRefresh = { }
            )
        }
    }
}

@Preview
@Composable
private fun EditTaskContentEmptyPreview() {
    SunflowerTheme {
        Surface {
            StartContent(
                viewModel = null,
                scaffoldState = null,
                loading = false,
                empty = true,
                Task(
                    title = "Title",
                    description = "Description",
                    isCompleted = false,
                    id = "ID"
                ),
//                onTaskCheck = { },
//                onRefresh = { }
            )
        }
    }
}
@Preview
@Composable
private fun CircularProgressAnimatedPreview() {
    CircularProgressAnimated()
}

@Preview
@Composable
private fun PaginationExamplePreview() {
    PaginationExample({}, null, null)
}
